import os
from flask import current_app
from sqlalchemy import desc

from applications.common.helper import ModelFilter
from applications.extensions import db
from applications.extensions.init_upload import photos, files
from applications.models import Photo
from applications.schemas import PhotoSchema
from applications.common.curd import model_to_dicts


def get_photo(page, limit, types):
    mf = ModelFilter()
    if types != "":
        mf.vague(field_name="types", value=types)
    photo = Photo.query.filter(mf.get_filter(model=Photo)).order_by(desc(Photo.create_time)).paginate(page=page,
                                                                                                      per_page=limit,
                                                                                                      error_out=False)
    count = Photo.query.filter(mf.get_filter(model=Photo)).count()
    data = model_to_dicts(schema=PhotoSchema, data=photo.items)
    return data, count


def upload_one(photo, mime):
    # 图片和其他文件分开存储
    if "image" in mime:
        filename = photos.save(photo)
        file_url = photos.url(filename)
        types = "image"
        upload_url = current_app.config.get("UPLOADED_PHOTOS_DEST")
    else:
        filename = files.save(photo)
        file_url = files.url(filename)
        if "video" in mime:
            types = "video"
        elif "audio" in mime:
            types = "audio"
        else:
            types = "files"
        upload_url = current_app.config.get("UPLOADED_FILES_DEST")

    size = os.path.getsize(os.path.join(upload_url, filename))
    photo = Photo(name=filename, href=file_url, mime=mime, upurl=os.path.join(upload_url, filename), size=size,
                  types=types)
    db.session.add(photo)
    db.session.commit()
    return file_url


def delete_photo_by_id(_id):
    thisphoto = Photo.query.filter_by(id=_id).first()
    photo_name = thisphoto.name
    photo_mime = thisphoto.mime
    photo = Photo.query.filter_by(id=_id).delete()
    db.session.commit()
    delete_photo_files(photo_name, photo_mime)
    return photo


def delete_photo_files(photo_name, photo_mime):
    """ 根据文件类型从不同路径删除文件，如果是图片则同时删除缩略图 """
    upload_url = current_app.config.get("UPLOADED_PHOTOS_DEST")
    tpath = os.path.join(upload_url, 'thumbnail')
    fileupload_url = current_app.config.get("UPLOADED_FILES_DEST")
    if "image" in photo_mime:
        os.remove(os.path.join(upload_url, photo_name))
        justname = photo_name[::-1]
        justname = justname[justname.find('.') + 1: len(justname)][::-1]
        for file in os.listdir(tpath):
            if file.find(justname) == 0:
                os.remove(os.path.join(tpath, file))
    else:
        os.remove(os.path.join(fileupload_url, photo_name))
